var twbAddOrderPageVm  = new Vue({
    el: '#twbAddOrderPage',
    data:function() {
        return{
            //打开添加订单页面
            addOrderPageVisible: false,
            //防止重复添加订单:
            orderVisible:true,
            //添加订单包装类
            erpOrderItemDto:{erpOrder:{},erpOrderItemList:[]},
            title:'添加订单',
            //订单对象
            erpOrder:{memberName:'',shipName:'',shipMobile:'',orderCreatetime:'',acceptOrderUser:'',shipArea:'',shipAddr:''},
            //商品明细
            erpOrderItemData:[{name:'',addon:'',unit:'',nums:1,copy:1,price:'',amount:''}],
            //商品明细勾选行
            itemCurrentRow:{},
            //查询的产品集合
            productData:[],
            //客户信息
            storeMemberData:[],
            //会员折扣
            discountRate:0,
            //加载客户
            loading:false,
            //省市区
            areaCascader:[],
            itemForm:[],
            //添加订单校验规则
            addRules:{
                memberName:{ required: true, //是否必填
                    message: '请选择客户', //规则
                    trigger: 'blur'  //何事件触发
                },
                shipName:[
                    { required: true,message:'请输入联系人',trigger: 'blur'}
                ],
                orderCreatetime:[
                    { required: true,message:'请选择接单时间',trigger: 'blur'}
                ],
                shipMobile:[{ required: true,pattern: /^1[345678]\d{9}$/, message:'请输入正确的手机号', trigger: 'blur'},
                ]
            },
            itemRules:{
                name:[
                    {required: true, message: '商品名称不能为空', trigger: 'change'},
                ],
                nums:[
                  {required: true,pattern:/^([1-9][0-9]*(\.\d{1,2})?)|(0\.\d{1,2})$/, message: '请输入正确数量', trigger: 'blur'},
                ],
                copy:[
                      {required: true,pattern:/^[1-9]\d*$/, message: '请输入正确份数,必须为正整数', trigger: 'blur'},
                ],
                amount:[
                    {required: true,pattern:/^([1-9][0-9]*(\.\d{1,2})?)|(0\.\d{1,2})$/, message: '请输入正确总价', trigger: 'blur'},
                ],
                price:[{required: true,pattern:/^([1-9][0-9]*(\.\d{1,2})?)|(0\.\d{1,2})$/, message: '请输入正确单价', trigger: 'blur'},]
            },
            //支付方式
            payTypeData:[],
            //表单对齐方式
            labelPosition: 'right',
            //地区用于选择收货地区
            area:[],
            salesManList:[],
            acceptOrderUserData:[],
            //是否可挂账
            credit:false,
            memberLoading: false,
        }
    },
    mounted:function(){
        this.loadData();
    },
    methods: {
        /* 初始化 */
        loadData: function () {
            var self=this;
            self.orderVisible=true;
            var date=self.orderCreatetimeFormat();
            self.areaCascader=[];
            self.erpOrderItemData=[{name:'',addon:'',unit:'',nums:1,copy:1,price:'',amount:''}];
            self.itemForm.erpOrderItemData=self.erpOrderItemData;
            self.erpOrder={storeMemberId:'',memberName:'',shipName:'',shipMobile:'',onCredit:false
                ,orderCreatetime:date,acceptOrderUser:'',shipArea:'',shipAddr:'',shipAreaId:'',deposit:false,payed:0};
            var url="twbOrder/erporder/addData"
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                success: function(r){
                    if(r.code === 0){
                        self.acceptOrderUserData=r.acceptOrderUserData;
                        self.erpOrder.acceptOrderUser=r.currentUser;
                        //必须在页面加载完后赋值
                        self.erpOrder.orderCreatetime=date;
                        self.area=JSON.parse(r.area);
                    }else{
                        alert(r.msg);
                    }
                }
            });
            self.addOrderPageVisible=true;
            //清空校验
            self.$nextTick(function () {
                this.$refs['addForm'].resetFields(); //此方法需要模态框加载完成后才可以执行
            });
        },
        /* 更改省市区 */
        handleAreaChange:function(val){
            var values = val.join(',').split(',');
            var areaId = values[val.length - 1];
            var lableVal =this.getCascaderObj(val, this.area);
            this.erpOrder.shipAreaId = areaId;
            var area = lableVal.join(',').replace(new RegExp(',', 'g'), ' ');
            this.erpOrder.shipArea = area;
        },
        getCascaderObj(val, opt) {
            return val.map(function (value, index, array) {
                for (var itm in opt) {
                    if (opt[itm].value == value) {
                        var label = opt[itm].label;
                        opt = opt[itm].children;
                        return label;
                    }
                }
                return null;
            });
        },
        //远程搜索客户
        searchMember:function(query){
            if(query.type=='focus'){
                query='';
            }
            debugger
            var self=this;
            var url="twbOrder/erporder/searchMember"
            var param={'name':query.trim()};
            setTimeout(function () {
                $.ajax({
                    type: "POST",
                    url: baseURL + url,
                    contentType: "application/json;charset=UTF-8",
                    data:JSON.stringify(param),
                    success: function(r){
                        if(r.code === 0){
                            self.storeMemberData=r.storeMemberData;
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            },250)
        },
        selectStoreMember:function(val){
            if(val!=null&&val!=undefined){
                for (var i=0;i<this.storeMemberData.length;i++){
                    var item=this.storeMemberData[i];
                    if(item.storeMemberId==val){
                        this.erpOrder.storeMemberId=item.storeMemberId;
                        this.erpOrder.memberName=item.name;
                        this.erpOrder.shipName=item.nickname;
                        this.erpOrder.memberId=item.memberId;
                        this.erpOrder.shipMobile=item.mobile;
                        this.erpOrder.shipAddr=item.addr;
                        this.credit=item.hangsAccountCustomer;
                        this.erpOrder.onCredit=item.hangsAccountCustomer;
                        if(val.discountRate){
                            this.discountRate=item.discountRate;
                        };
                    }
                }
            }
        },

        save:function(){
            var self=this;
            self.erpOrderItemDto.erpOrder=self.erpOrder;
            if(self.erpOrderItemData.length==0){
                alert("商品明细不能为空");
                return;
            }
            self.erpOrderItemDto.erpOrderItemList=self.itemForm.erpOrderItemData;
            var url="twbOrder/erporder/save"
            this.$refs["addForm"].validate(function (valid){
               if(valid){
                   self.$refs["itemForm"].validate(function (valid) {
                       if(valid){
                           self.orderVisible=false;
                           $.ajax({
                               type: "POST",
                               url: baseURL + url,
                               contentType: "application/json",
                               data:JSON.stringify(self.erpOrderItemDto),
                               success: function(r){
                                   if(r.code === 0){
                                       alert('操作成功', function(index){
                                           self.orderVisible=true;
                                           self.reload();
                                       });
                                   }else{
                                       alert(r.msg);
                                       self.orderVisible=true;
                                   }
                               }
                           });
                       }
                   })
               }
           });
        },
        //跳转到订单列表
        reload:function(){
           /* var self=this;
            self.addOrderPageVisible=false;*/
            window.parent.vm.zyRouter({
                url:'modules/order/twbOrder.html',
                name:'订单列表',
                blank: true,
                closeBlank:true,
                vmName:'twbOrderVm',
                params:{},
            });
        },
        //改变产品明细数量
        handleNums:function(value,row){
            var  reg = /[^\d\.]/g;
            if (value && new RegExp(reg).test(value)) {//非数字
                this.$message({
                    message: '请输入正确的数字',
                    type: 'warning'
                })
                row.nums=1;
                return;
            }
            row.amount=value*row.price*row.copy;
            if(isNaN(row.amount)){
                row.amount=0;
            }
        },
        //改变价格
        handlePrice:function(value,row){
            var  reg = /[^\d\.]/g;
            if (value && new RegExp(reg).test(value)) {//非数字
                this.$message({
                    message: '请输入正确的数字',
                    type: 'warning'
                })
                return;
            }
            row.amount=row.price*row.nums*row.copy;
            if(isNaN(row.amount)){
                row.amount=0;
            }
        },
        //处理单位
        handleUnit:function(value,row){
            var  reg = /[@#\$%\^&\*]+/g;
            if (value && new RegExp(reg).test(value)) {
                this.$message({
                    message: '请输入正确单位，不允许包含特殊字符',
                    type: 'warning'
                })
                row.unit='';
                return;
            }
        },
        //改变总价
        handleAmount:function(value,row){
            var  reg = /[^\d\.]/g;
            //校验数量
            if (row.nums && new RegExp(reg).test(row.nums)||row.nums==0) {//非数字
                this.$message({
                    message: '请确认数量是否正确',
                    type: 'warning'
                })
                row.amount=''
                return;
            }
            //校验数量
            if (row.copy && new RegExp(reg).test(row.copy)||row.copy==0) {//非数字
                this.$message({
                    message: '请确认份数是否正确',
                    type: 'warning'
                })
                row.amount='';
                return;
            }
            var  reg = /[^\d\.]/g;
            if (value && new RegExp(reg).test(value)) {//非数字
                this.$message({
                    message: '请输入正确的数字',
                    type: 'warning'
                })
                row.amount=row.price*row.nums*row.copy;
                return;
            }
            row.price=((value/row.nums)/row.copy).toFixed(3);
        },
        //新增明细
        addItem:function(){
            var item={name:'',addon:'',unit:'',nums:1,copy:1,price:'',amount:''};
            this.erpOrderItemData.push(item);
        },
        //删除明细
        delItem:function(index,rows){
            rows.splice(index, 1);
        },
        querySearchProduct:function(queryString, cb){
        var self=this;
        var item={"name":queryString}
        setTimeout(function () {
            $.ajax({
                type: "POST",
                url: baseURL + "twbOrder/erporder/querySearchProduct",
                contentType: "application/json;charset=UTF-8",
                data:JSON.stringify(item),
                success: function(r){
                    if(r.code == 0){
                        self.productData=r.productData;
                        cb( self.productData);
                    }else{
                        alert(r.msg);
                    }
                }
            });
        } ,400);
        },

        //选择产品名称
        handleSelectProduct:function(item,row){
            row.name=item.name;
            row.addon=item.productInfo;
            row.price=item.totalPrice;
            row.goodsId=item.goodsId;
            row.productId=item.productId;
            row.unit=item.unit;
            row.nums=1;
            row.copy=1;
            row.amount=item.totalPrice*row.nums;
            row.pmtGoods=0;
        },

        //格式化date_time-picker数据
        orderCreatetimeFormat:function () {
            var date=new Date();
            var Y=date.getFullYear();
            var M=date.getMonth()+1
            M=(M<10?'0'+M:M);
            var D=(date.getDate()<10?'0'+date.getDate():date.getDate());
            var h=(date.getHours()<10?'0'+date.getHours():date.getHours());
            var m=(date.getMinutes()<10?'0'+date.getMinutes():date.getMinutes());
            var s=(date.getSeconds()<10?'0'+date.getSeconds():date.getSeconds());
            return Y+'-'+M+'-'+D+' '+h+':'+m+':'+s
        },
    }
})